#include <bits/stdc++.h>
// 2025/02/06
// tag:
// Author: Zhang Muen
using namespace std;

using int64 = int64_t;

#define int long long

int n, feel[300001], l[300001], r[300001];

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> feel[i];
    stack<int> st;
    for (int i = 1; i <= n; i++) {
        r[i] = n + 1;
        while (!st.empty() && feel[st.top()] > feel[i])
            r[st.top()] = i, st.pop();
        st.push(i);
    }
    st = stack<int>();
    for (int i = n; i >= 1; i--) {
        l[i] = 0;
        while (!st.empty() && feel[st.top()] >= feel[i])
            l[st.top()] = i, st.pop();
        st.push(i);
    }
    int ans = 0;
    for (int i = 1; i <= n; i++)
        ans -= (r[i] - i) * (i - l[i]) * feel[i];
    st = stack<int>();
    for (int i = 1; i <= n; i++)
        r[i] = n + 1;
    for (int i = 1; i <= n; i++) {
        while (!st.empty() && feel[st.top()] < feel[i])
            r[st.top()] = i, st.pop();
        st.push(i);
    }
    memset(l, 0, sizeof(l));
    st = stack<int>();
    for (int i = n; i >= 1; i--) {
        while (!st.empty() && feel[st.top()] <= feel[i])
            l[st.top()] = i, st.pop();
        st.push(i);
    }
    for (int i = 1; i <= n; i++)
        ans += (r[i] - i) * (i - l[i]) * feel[i];
    cout << ans;
    return 0;
}